#!/usr/bin/env python3
# Copyright (c) 2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

import click
import os

plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')
cli_help = 'fancy command-line interface'


class MyCLI(click.MultiCommand):

    def list_commands(self, ctx):
        rv = []
        blacklist = ('__init__.py',)
        for filename in os.listdir(plugin_folder):
            if filename in blacklist:
                continue
            if filename.endswith('.py'):
                rv.append(filename[:-3])
        rv.sort()
        return rv

    def get_command(self, ctx, name):
        ns = {}
        fn = os.path.join(plugin_folder, name + '.py')
        with open(fn) as f:
            code = compile(f.read(), fn, 'exec')
            eval(code, ns, ns)
        return ns['cli']


def main():
    cli = MyCLI(help=cli_help)
    cli()


if __name__ == '__main__':
    main()
